<template>
    <d2-container>
        <el-main>

            <el-form ref="productOrderForm" :model="productOrderForm" label-width="80px" label-position="left"
                     :rules="formRules">

              
                <el-form-item label="采购列表" prop="productOrder">

                    <el-button
                            @click="selectProduct"
                            style="float:left;margin:10px"
                            icon="el-icon-plus"
                            size="small"
                            type="primary"
                            >
                        添加采购的商品
                    </el-button>

                    <el-dialog title="商品列表" :visible.sync="status.selectProduct">
                         <el-select v-model="search.schoolType" filterable placeholder="采购源" @change='schoolChange' size='small' style='width: 35%;display: block;'>
                          <el-option
                            v-for="item in schoolTypeList"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value"
                          ></el-option>
                        </el-select>
                        <el-input placeholder="请输入教材名称" v-model="search.searchProductName" size="small" style='width: 50%;display: inline-block;'>
                            <!-- <el-button slot="append" icon="el-icon-search" @click="searchProduct"></el-button> -->
                        </el-input>
                       
                        <el-select v-model="search.productCategory" filterable placeholder="搜索商品分类" @change='categoryChange' size='small' style='margin-left:5%;width: 35%;display: inline-block;'>
                          <el-option
                            v-for="item in productCategoryList"
                            :key="item._id"
                            :label="item.name"
                            :value="item._id"
                          ></el-option>
                        </el-select>
                        <el-button  icon="el-icon-search" @click="searchProduct" style='display: inline-block;width: 10%' size='small' type='primary'></el-button>

                        <el-table :data="productList">
                            <el-table-column property="name" label="商品名称"></el-table-column>
                            <el-table-column property="typeText" label="类型"></el-table-column>
                            <el-table-column prop="wholeSalePrice" label="批发价(元)"></el-table-column>
                            <el-table-column prop="storage" label="库存"></el-table-column>
                            <el-table-column  label="操作">
                                <template slot-scope="scope">
                                    <el-button v-if="scope.row.storage > 0" @click="addProduct(scope.row)" type="text">添加</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="status.selectProduct = false">确认</el-button>
                        </div>
                    </el-dialog>

                    <el-table :data="productOrderForm.productOrder" border style="width: 100%">

                        <el-table-column prop="product.name" label="商品名称"></el-table-column>
                        <!-- <el-table-column prop="productCategory[0].name" label="商品种类"></el-table-column> -->
                        <el-table-column property="product.typeText" label="类型"></el-table-column>
                        <el-table-column prop="product.wholeSalePrice" label="批发价(元)" ></el-table-column>
                        <el-table-column prop="product.storage" label="库存" disabled="disable"></el-table-column>
                        <el-table-column label="数量">
                            <template slot-scope="scope">
                                <input v-model="productOrderForm.productOrder[scope.$index].amount"
                                       style="width:50px" type="number" min="0"
                                       @change="countChange(scope.$index)" :disabled="disabled"></input>
                            </template>
                        </el-table-column>
                        <el-table-column  label='小计(元)'>
                            <template slot-scope="scope">
                            {{parseFloat(productOrderForm.productOrder[scope.$index].amount * productOrderForm.productOrder[scope.$index].product.wholeSalePrice).toFixed(2)}}
                             </template>
                    </el-table-column>
                        
                        <el-table-column fixed="right" label="操作">
                            <template slot-scope="scope">
                                <el-button @click="deleteClick(scope.$index)" type="text" size="small"
                                           >删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item>
            



            </div>
        </el-form-item>


                <el-form-item label="支付方式" prop="payWay">
                    <el-radio-group v-model="productOrderForm.payWay" >
                        <el-radio :label="0">现金</el-radio>
                        <el-radio  :label="1">银行卡</el-radio>
                        <el-radio  :label="2">支付宝</el-radio>
                        <el-radio  :label="3">微信</el-radio>
                    </el-radio-group>
                </el-form-item>


              <el-form-item  label='备注'>
                
                <el-input style="position: relative;;;display: inline-block;width: 50%;" :rows="7" v-model='productOrderForm.memo' placeholder='备注信息' type='textarea'>
                    
                </el-input>
              </el-form-item>
               


               
                

                <el-form-item label="实收合计">
                    {{parseFloat(productOrderForm.total).toFixed(2)}}
                </el-form-item>

            </el-form>


          


        </el-main>
        <el-footer style="text-align: center">
            <el-button type="primary" @click="submit">提交</el-button>
        </el-footer>


    </d2-container>


</template>
<script>
    import request from "@/plugin/axios";
    import {mapState} from "vuex";

    export default {
        data() {
            return {
                formRules: {


                    productOrder: [
                        {type: 'array', required: true, message: '请选择采购商品', trigger: 'blur'}
                    ],
                    payWay: [
                        {required: true, message: '请选择支付方式', trigger: 'change'}
                    ],
                    

                },

                productOrderForm: {

                    //购买者类型
                    
                    productOrder: [],
                    payWay: 0,
                    total : 0,
                    memo : ''
                },
                showStaff :false,
                options: {
                    payStatusOption: [
                        {
                            label: '待支付',
                            value: 0
                        },
                        {
                            label: '已支付',
                            value: 1
                        }
                    ],
                    schoolOption: []
                },
                status: {
                    selectStudent: false,
                    selectSchool: false,
                    selectStaff: false,
                    selectProduct: false,
                },
                schoolList: [],
                studentList: [],
                staffList: [],
                productList: [],
                schoolTypeList : [{value:'primary',name:'主校'},{value:'main',name:'弈飞总部'}],
                search: {
                    searchStudentName: undefined,
                    searchStaffName: undefined,
                    searchProductName: undefined,
                    productCategory :undefined,
                    schoolType : 'primary'
                },
                select: {
                    selectStudentList: [],
                    selectStaffList: [],
                    selectSchoolList: []
                },
                editShow: false,
                disabled: false,
                id: undefined,
                searchName: undefined,
                searchCount: undefined,
                searchSchoolName: undefined,
                searchSchoolCount: undefined,
                searchStudentCount: undefined,
                searchStaffCount: undefined,
                student: undefined,
                productStaff: undefined,
                total:0,
                headquarter : undefined

            };
        },
        computed: {
            ...mapState('d2admin/user', ['info']),
            // total: function () {
            //     let t = 0;
            //     this.productOrderForm.productOrder.forEach((value, index) => {
            //         t = t + parseInt(value.count) * value.sellingPrice
            //     });
            //     this.productOrderForm.total = t;
            //     return t;
            // },
            real: function () {
                let t = 0
                t = this.total - this.productOrderForm.discount;
                return t;
            }
        },
        methods: {
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            /**
             * school选择相关
             */





            /**
             *
             * product相关
             *
             */

             schoolChange(){
                if (this.productOrderForm.productOrder.length != 0){
                    this.$confirm('是否继续','切换采购源头会清空采购列表').then(()=>{
                        this.productOrder = []
                        this.total = 0
                        this.productList = []
                        this.searchName = ''

                        this.productOrderForm=  {                    
                    productOrder: [],
                    payWay: 0,
                    total : 0,
                    memo : ''
                }
                this.getCategoryList(this.search.schoolType)
                this.search.productCategory = undefined
                    }).catch(()=>{
                        if (this.search.schoolType == 'main'){
                            this.search.schoolType = 'primary'
                        }
                        else{
                            this.search.schoolType = 'main'
                        }
                    })
                }
                else{
                    this.productList = []
                    this.productCategoryList =  [{_id:undefined,name:'全部'}]
                    this.getCategoryList(this.search.schoolType)
                    this.search.productCategory = undefined
                }
             },

            getCategoryList(type) {
                let data = {}
                data.school = [type]
                data.pageSize = 99999
                // if ((this.info.school[0].primarySchool != null ) || (this.info.school[0].primarySchool != undefined)){
                //     data.school = ['primary']
                // }
                request({
                    url: "/productCategory/getProductCategoryList",
                    method: "post",
                    data: data
                }).then(res => {
                  this.productCategoryList = [{_id:undefined,name:'全部'}]
                this.productCategoryList = this.productCategoryList.concat(res.data.productCategory);
                });
            },

            searchProduct() {
                this.getProductList(1);
            },
            getProductList(page) {
                let data = {}
                data.page = 1
                data.size = 999999
                data.name = this.search.searchProductName
                data.school = ['main']
                if ((this.info.school[0].primarySchool != null ) && (this.info.school[0].primarySchool != undefined)){
                    data.school = ['primary']
                }
                if (this.search.schoolType !=undefined){
                    data.school = [this.search.schoolType]
                }
                if (this.search.productCategory != undefined){
                    data.category = this.search.productCategory
                }
                
                request({
                    url: "/product/getProductList",
                    method: "post",
                    data: data
                }).then(res => {
                    if (res.code == 200) {
                        res.data.product.forEach(e=>{
                            e.typeText = e.productCategory.map(a=>{return a.name}).join(',')
                        })
                        this.productList = res.data.product
                        this.searchCount = res.data.count
                    }
                });
            },
            addProduct(e) {
              
                if (this.productOrderForm.productOrder.map(event => {
                    return event.product._id
                }).indexOf(e._id) == -1) {
                    let temp = {}
                    temp.product = e
                    temp.amount = 0
                    this.productOrderForm.productOrder.push(temp)
                } else {
                    this.$message({
                        showClose: true,
                        message: '已经添加这个商品了哦',
                        type: 'error'
                    });
                }
            },
            deleteClick(e) {
                this.productOrderForm.productOrder.splice(e, 1)
                let total = 0
                    for (let i = 0; i < this.productOrderForm.productOrder.length; i++) {
                           total += this.productOrderForm.productOrder[i].product.wholeSalePrice * this.productOrderForm.productOrder[i].amount  
                    }
                    this.productOrderForm.total = total
                    this.total = total
            },

            /**
             *
             *
             *
             */

            submit() {
              if (this.productOrderForm.productOrder.length == 0){
                this.$alert('','请选择采购商品')
                return false
              }
              let sss  = this.productOrderForm.productOrder.filter(function(e){return e.amount == 0})
              if (sss.length > 0){
                this.$alert('','商品数量不能为0')
                return false
              }
              this.$confirm('请确认本校商品列表有同名的商品,否则会创建新商品，所有价格为100元。','确认要发送请求吗',{
                confirmButtonText : '确定',
                cancelButtonText : '取消',
                type: "warning"
              }).then(()=>{
                let data = {}
                data.toSchool = this.school
                data.school = this.search.schoolType
                data.staff = this.staff || null
                data.productOrder = this.productOrderForm.productOrder
                data.total = this.productOrderForm.total
                data.payWay = this.productOrderForm.payWay
                data.memo = this.productOrderForm.memo
                console.log(data.school,'ssss')
               request({
                    url: "/productOrder/addProductRequest",
                    method: "post",
                    data: data
                }).then(res => {
                    if (res.code == 200) {
                        this.refresh = true
                        this.productOrderForm = {

                    //购买者类型
                    
                    productOrder: [],
                    payWay: 0,
                    total : 0,
                    memo : ''
                }
                        this.$alert('','发送请求成功!',{}).then(res=>{
                          this.$router.back(-1)
                         
                        })
                    }
                });
              })
              
                
                
            },

            edit() {
                this.disabled = false;
            },

            currentChange(e) {
                this.getProductList(e);
            },

            studentCurrentChange(e) {
                this.getStudentList(e);
            },

            staffCurrentChange(e) {
                this.getStaffList(e);
            },

            countChange(index) {
                let count = this.productOrderForm.productOrder[index].amount
                let storage = this.productOrderForm.productOrder[index].product.storage

                if (count < 0 || count > storage) {

                    // this.productOrderForm.productOrder[index].count = 1

                    this.$message({
                        showClose: true,
                        message: '数量不合法，请重新输入',
                        type: 'error'
                    });
                    if (count > storage){
                      this.productOrderForm.productOrder[index].amount = storage
                    }

                } else{
                    let total = 0
                    for (let i = 0; i < this.productOrderForm.productOrder.length; i++) {
                           total += this.productOrderForm.productOrder[i].product.wholeSalePrice * this.productOrderForm.productOrder[i].amount  
                    }
                    this.productOrderForm.total = total
                    this.total = total
                }

            },
            selectProduct(){
                this.status.selectProduct = true
                }


        },
        beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                  v.productOrderForm = to.meta.productOrderForm
                  to.meta.productOrderForm = undefined
                  to.meta.keep = undefined
                })
            }
            else{
                next()
            }
            console.log(to,from,'toto')
            next()

        },
        beforeRouteLeave(to,from,next){
          if (this.$route.query.id == undefined) {
            from.meta.keep = true
            from.meta.productOrderForm = this.productOrderForm      
          }
          if (this.refresh){
            to.meta.refresh = 'a'
          }

          next()
        },

        created() {
            this.getCategoryList('primary')
          this.school = this.info.school[0]._id
            this.staff = this.info.staff == undefined ? null : this.info.staff._id
            this.staffname = this.info.staff == undefined ? '' : this.info.staff.name

            if ((this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2)){
                this.headquarter = 1
            }

            else{
                this.productOrderForm.buyer = 2
            }
            
            this.options.schoolOption = this.info.school;
            this.productOrderForm.fromSchool = this.options.schoolOption[0]._id;

            //零时修正
            if (this.info.role.indexOf('root') > -1) {
                this.productOrderForm.fromSchool = this.options.schoolOption[1]._id;
            }


            if (this.$route.query.id != undefined) {
                this.editShow = true;
                this.disabled = true;
                this.getProductOrderOne(this.$route.query.id)

            }
        }
    }
</script>
